from google.appengine.ext import blobstore
from google.appengine.ext import db
from google.appengine.ext.webapp import blobstore_handlers

from utils import *
from CONFIG import *
from datatypes import *

"""
Handles uploads. The blob is taken care of by BlobstoreUploadHandler,
this takes care of creating the Asset object.
"""
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    
    def post(self):
        # get files submitted in the request
        blob_info = self.get_uploads("asset_file")[0]
        
        # Create a new Asset Object containing the blob's infomation
        asset = Asset()
        asset.asset_key = blob_info.key()
        asset.created_by = users.get_current_user().nickname()

        # Has a directory parameter been passed?
        directory = self.request.get("directory_id")
        if directory == "":
            dir = Directory.get_root()
        else:
            dir = Directory.get_by_id(int(self.request.get("directory_id")))
            
        # Set the asset's directory
        asset.directory = dir
        
        # Save the Asset
        asset.put()
        
        # redirect back to the management page
        self.redirect(GAPYCDN_CONFIG["base_url"] + "manage")
